package com.woniuxy.handler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.util.*;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Map;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    //使用此工具类的对象进行序列化操作
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @SneakyThrows
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从请求头中获取Authorization信息
        String authorization = request.getHeader(CONSTANT.JWT);
        //如果授权信息为空，返回前端
        if(null==authorization){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(
                    new ResponseData<>().fail(ResponseEnum.LOGIN_FAIL)));
            return;
        }
        //如果Authorization信息不为空，去掉头部的Bearer字符串
        String token = authorization.replace("Bearer ", "");
        Map userInfo = JWTUtil.getUserInfo(token);
        Long userId = (Long) userInfo.get("userId");

        //redis中删除token，这是关键点
        redisTemplate.delete(CONSTANT.LOGIN_USER_JWT +userId);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSON.toJSONString(
                new ResponseData<>().fail(ResponseEnum.LOGIN_FAIL)));

    }
}



